import React, { Component } from 'react';
import { Stepper, Toast } from 'antd-mobile';
import './cartItem.less';

import * as common from 'common/common.js';
import * as userApi from 'common/api/UserApi.js';

/**
 * 购物车子组件:购物车子项
 * @param {cartInfo} 数据
 * @param {cartInfo.goodsImage} 商品图片
 * @param {cartInfo.goodsName} 	商品名称
 * @param {cartInfo.goodsTitle} 商品描述
 * @param {cartInfo.goodsPriceStr} 商品价格
 */
class CartItem extends Component{
	
	constructor(props) {
	    super(props);
	    this.state = {
	      	val: this.props.cartInfo.goodsNum,
	    };
  	}
	
	//数值改变
	cartNumChange = (val) => {
		Toast.loading("", common.TIPS_LOADING_DURATION);
		const { cartInfo, cartIds } = this.props;
		//修改购物车数量
		userApi.updateCart({
			cartId: cartInfo.id,
			goodsNum: val,
		}).then(result => {
			Toast.hide();
			if(result.code == common.SUCCESS){
				this.setState({ val });
				this.props.checkCart(true, cartInfo.id);
				this.props.getMemberCartList();
			}
		})
	}
	
	//选中购物车
	checkCart = () => {
		const { cartInfo, cartIds } = this.props;
		if(common.isInArray(cartIds, cartInfo.id)){
			this.props.checkCart(false, cartInfo.id);
		}else{
			this.props.checkCart(true, cartInfo.id);
		}
	}
	
	render(){
		const { val } = this.state;
		const { cartInfo, cartIds } = this.props;
		var checkImg = common.isInArray(cartIds, cartInfo.id) ? "assets/img/select.png" : "assets/img/unselect.png";
		return(
			<div className="cartItemBox">
				<div className="cartItem list_item">
					<div className="left" onClick={this.checkCart.bind(this)}>
						<img src={checkImg}/>
					</div>
					<div className="content">
						<div className="list_item_img">
							<img src={cartInfo.goodsPic}/>
						</div>
						<div className="list_item_info">
							<span className="name">{cartInfo.goodsName}</span>
							<div className="list_item_info_other">
								<span className="price">¥{common.fenToYuan(cartInfo.goodsPrice)}</span>
								<Stepper
			              showNumber
			              max={99}
			              min={1}
			              value={val}
			              useTouch={false}
			              onChange={this.cartNumChange}
			          />
							</div>
						</div>
					</div>
				</div>
			</div>
		)
	}
}

export default CartItem;